﻿
Imports System.Threading

Namespace control_c
    Public Module _control_c
        Public Event press(ByRef cancel As Boolean)
        Private _blocking As Int32
        Private _pressed As Boolean

        Public Function pressed() As Boolean
            Return _pressed
        End Function

        Public Sub block()
            k_assert(Interlocked.Increment(_blocking) > 0)
        End Sub

        Public Sub release()
            k_assert(Interlocked.Decrement(_blocking) >= 0)
        End Sub

        Public Function blocking_count() As Int32
            Return _blocking
        End Function

        Public Function blocking() As Int32
            Return blocking_count() > 0
        End Function

        Public Sub register()
            'trigger sub new()
        End Sub

        Sub New()
            _pressed = False
            AddHandler Console.CancelKeyPress,
                       Sub(sender As Object, arg As ConsoleCancelEventArgs)
                           RaiseEvent press(arg.Cancel())
                           If Not arg.Cancel() Then
                               _pressed = True
                               While blocking()
                                   sleep()
                               End While
                           End If
                       End Sub
        End Sub
    End Module
End Namespace
